package com.sjh.baseutils

import android.content.Context
import com.tencent.mmkv.MMKV
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * 使用委托，可以保存基本类型到sp
 * @author Extends
 * @date 2020/6/4
 */
class Preference<T>(val context: Context, val name: String, val default: T, private val defaultFileName: String = "kotlinDefault") :
    ReadWriteProperty<Any?, T> {
    private val kv = MMKV.defaultMMKV()

    companion object {
        fun initMMKV(context: Context) {
             MMKV.initialize(context)
        }

    }


    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        val res: Any = when (default) {
            is Long -> kv.decodeLong("$defaultFileName-$name", default)
            is String -> kv.decodeString("$defaultFileName-$name", default)
            is Int -> kv.decodeInt("$defaultFileName-$name", default)
            is Boolean -> kv.decodeBool("$defaultFileName-$name", default)
            is Float -> kv.decodeFloat("$defaultFileName-$name", default)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }
        return res as T
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        saveValue(value)
    }

    fun <U> saveValue(value: U) {
        when (value) {
            is Long -> kv.encode("$defaultFileName-$name", value as Long)
            is String -> kv.encode("$defaultFileName-$name", value as String)
            is Int -> kv.encode("$defaultFileName-$name", value as Int)
            is Boolean -> kv.encode("$defaultFileName-$name", value as Boolean)
            is Float -> kv.encode("$defaultFileName-$name", value as Float)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }
    }
}
